package org.sauceggplant;

import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

/**
 * 解密界面
 *
 * @author jacob
 * @version 0.1
 */
public class DPanel extends JPanel {

    private JFileChooser dFileChooser = new JFileChooser();

    private JProgressBar dProgressBar = new JProgressBar();

    /**
     * 解密
     */
    private Decrypt decrypt;

    public DPanel() {
        this.setLayout(new BorderLayout());
        dFileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        dFileChooser.setMultiSelectionEnabled(false);
        dFileChooser.setApproveButtonText("解密");
        dFileChooser.setFileFilter(new FileFilter() {
            @Override
            public boolean accept(File f) {
                return f.getName().endsWith(".edata");
            }

            @Override
            public String getDescription() {
                return "Encrypt Data (*.edata)";
            }
        });

        dProgressBar.setMinimum(0);
        //dProgressBar.setMaximum(100);
        dProgressBar.setStringPainted(true);
        dProgressBar.setOrientation(SwingConstants.HORIZONTAL);

        decrypt = new Decrypt(dProgressBar);
        dFileChooser.addActionListener(new DecryptListener(dFileChooser, decrypt));

        this.add(dFileChooser, BorderLayout.CENTER);
        this.add(dProgressBar, BorderLayout.SOUTH);
    }

    public JFileChooser getdFileChooser() {
        return dFileChooser;
    }
}

class DecryptListener implements ActionListener {

    /**
     * 文件选择器
     */
    private JFileChooser fileChooser;

    /**
     * 解密
     */
    private Decrypt decrypt;

    public DecryptListener(JFileChooser fileChooser, Decrypt decrypt) {
        this.fileChooser = fileChooser;
        this.decrypt = decrypt;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if ("ApproveSelection".equals(e.getActionCommand())) {
            File file = fileChooser.getSelectedFile();
            if (file != null) {
                decrypt.decrypt(file);
                fileChooser.updateUI();
            }
        }
    }
}